package cn.cxyxj.code_auth_jwt_persistence_prod.auth.handler;

import cn.cxyxj.code_auth_jwt_persistence_prod.common.ApiResult;
import cn.cxyxj.code_auth_jwt_persistence_prod.common.ApiResultEnum;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登陆用户访问无权限资源时的回调
 * @author cxyxj
 */
public class CustomizeAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse resp, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        resp.setContentType(MediaType.APPLICATION_JSON_VALUE);
        PrintWriter out = resp.getWriter();
        out.write(JSONObject.toJSONString(ApiResult.fail(ApiResultEnum.AUTH_ERROR)));
        out.flush();
        out.close();
    }

}
